<template>
    <div class="enterprise-management">
        <!-- 左侧企业列表 -->
        <div class="sidebar">
            <div class="search-container">
                <div class="search-box">
                    <svg class="search-icon" width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                        <path
                            d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" />
                    </svg>
                    <input v-model="searchKeyword" type="text" placeholder="搜索企业..." class="search-input"
                        @input="handleSearch" />
                </div>
            </div>

            <div class="enterprise-list">
                <div v-for="enterprise in paginatedEnterprises" :key="enterprise.id" class="enterprise-item"
                    :class="{ active: selectedEnterprise?.id === enterprise.id }" @click="selectEnterprise(enterprise)">
                    <div class="enterprise-icon">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                            <path
                                d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
                        </svg>
                    </div>
                    <span class="enterprise-name">{{ enterprise.name }}</span>
                    <div v-if="selectedEnterprise?.id === enterprise.id" class="active-indicator">
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" />
                        </svg>
                    </div>
                </div>
            </div>

            <!-- 分页控件 -->
            <div class="pagination" v-if="totalPages > 1">
                <button class="page-btn" :disabled="currentPage === 1" @click="goToPage(currentPage - 1)">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z" />
                    </svg>
                </button>

                <span class="page-info">
                    {{ currentPage }} / {{ totalPages }}
                </span>

                <button class="page-btn" :disabled="currentPage === totalPages" @click="goToPage(currentPage + 1)">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z" />
                    </svg>
                </button>
            </div>
        </div>

        <!-- 主内容区域 -->
        <div class="main-content">
            <div v-if="selectedEnterprise" class="content-container">
                <div class="content-header">
                    <h1 class="enterprise-title">{{ selectedEnterprise.name }}</h1>
                    <div class="header-divider"></div>
                </div>

                <div class="modules-grid">
                    <div v-for="module in environmentalModules" :key="module.id" class="module-card">
                        <div class="card-content">
                            <div class="card-left">
                                <h3 class="module-title">{{ module.title }}</h3>
                                <p class="module-subtitle">{{ module.subtitle }}</p>
                                <button class="detail-btn" @click="viewDetails(module)">
                                    查看详情
                                </button>
                            </div>
                            <div class="card-right">
                                <div class="qr-code">
                                    <s-qrcode-draw :tag="codeInfo.tag" :text="codeInfo.text" :options="codeInfo.options" />

                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div v-else class="empty-state">
                <div class="empty-icon">
                    <svg width="64" height="64" viewBox="0 0 24 24" fill="currentColor">
                        <path
                            d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
                    </svg>
                </div>
                <h3 class="empty-title">请选择企业</h3>
                <p class="empty-description">从左侧列表中选择一个企业查看详细信息</p>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { getWrEnterpriseInfoAPI } from "@/api/modules/wrEnterpriseInfo/index";

const codeInfo = ref({
    id: 4,
    text: "123",
    docs: "高清晰度",
    tag: "img",
    options: {
        width: 120, // 二维码的宽度
        height: 120, // 二维码的高度
        color: {
            dark: "#000000", // 二维码的前景色（黑色）
            light: "#ffffff" // 二维码的背景色（白色）
        },
        margin: 4, // 边距，默认是 4
        scale: 4, // 模块大小，默认是 4
        quality: 1, // 质量，默认0.92
        errorCorrectionLevel: "H" // 错误修正级别：L (低), M (中), Q (较高), H (最高)
    }
})

// 类型定义
interface Enterprise {
    id: number
    name: string
    code: string
    industry: string
    location: string
   
}

interface EnvironmentalModule {
    id: number
    title: string
    subtitle: string
    qrData: string
}

// 响应式数据
const searchKeyword = ref('')
const selectedEnterprise = ref<Enterprise | null>(null)
const currentPage = ref(1)
const pageSize = 10
const isLoading = ref(false)

// 模拟大量企业数据
const allEnterprises = ref<Enterprise[]>([])

// 环境监管模块数据
const environmentalModules = ref<EnvironmentalModule[]>([
    {
        id: 1,
        title: '入河排污口',
        subtitle: '入河排污口',
        qrData: 'discharge-outlet'
    },
    {
        id: 2,
        title: '污染防治设施',
        subtitle: '污染防治设施',
        qrData: 'pollution-control'
    },
    {
        id: 3,
        title: '环境影响评价',
        subtitle: '环境影响评价',
        qrData: 'environmental-impact'
    },
    {
        id: 4,
        title: '危废贮存点',
        subtitle: '危废贮存点',
        qrData: 'hazardous-waste'
    },
    {
        id: 5,
        title: '排污许可',
        subtitle: '排污许可',
        qrData: 'discharge-permit'
    },
    {
        id: 6,
        title: '自行监测',
        subtitle: '自行监测',
        qrData: 'self-monitoring'
    }
])

// 计算属性
const filteredEnterprises = computed(() => {
    if (!searchKeyword.value) {
        return allEnterprises.value
    }

    return allEnterprises.value.filter(enterprise =>
        enterprise.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
        // enterprise.code.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
        // enterprise.industry.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
        // enterprise.location.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
})

const totalPages = computed(() => {
    return Math.ceil(filteredEnterprises.value.length / pageSize)
})

const paginatedEnterprises = computed(() => {
    const start = (currentPage.value - 1) * pageSize
    const end = start + pageSize
    return filteredEnterprises.value.slice(start, end)
})

// 方法
const generateMockEnterprises = (): Enterprise[] => {
    const enterprises: Enterprise[] = []
    const industries = ['制造业', '化工', '电力', '钢铁', '纺织', '食品', '医药', '建材', '造纸', '石化']
    const locations = ['上海市', '北京市', '广州市', '深圳市', '杭州市', '南京市', '苏州市', '武汉市', '成都市', '重庆市']

    for (let i = 1; i <= 500; i++) {
        enterprises.push({
            id: i,
            name: `企业${i}`,
            code: `ENT${i.toString().padStart(4, '0')}`,
            industry: industries[Math.floor(Math.random() * industries.length)],
            location: locations[Math.floor(Math.random() * locations.length)],
            
        })
    }

    return enterprises
}

const selectEnterprise = (enterprise: Enterprise) => {
    selectedEnterprise.value = enterprise
    // 生成二维码
    nextTick(() => {
        generateQRCodes()
    })
}

const handleSearch = () => {
    currentPage.value = 1
}

const goToPage = (page: number) => {
    if (page >= 1 && page <= totalPages.value) {
        currentPage.value = page
    }
}

const viewDetails = (module: EnvironmentalModule) => {
    console.log('查看详情:', module.title, '企业:', selectedEnterprise.value?.name)
    // 这里可以实现跳转到详情页面或打开弹窗
}

// 简单的二维码生成函数
const generateQRCode = (canvas: HTMLCanvasElement, data: string) => {
    const ctx = canvas.getContext('2d')
    if (!ctx) return

    // 清空画布
    ctx.fillStyle = '#ffffff'
    ctx.fillRect(0, 0, 120, 120)

    // 生成简单的二维码模式
    ctx.fillStyle = '#000000'
    const size = 120
    const moduleSize = size / 25

    // 生成伪随机模式（基于数据内容）
    let seed = 0
    for (let i = 0; i < data.length; i++) {
        seed += data.charCodeAt(i)
    }

    const random = (seed: number) => {
        const x = Math.sin(seed) * 10000
        return x - Math.floor(x)
    }

    for (let row = 0; row < 25; row++) {
        for (let col = 0; col < 25; col++) {
            const seedValue = seed + row * 25 + col
            if (random(seedValue) > 0.5) {
                ctx.fillRect(col * moduleSize, row * moduleSize, moduleSize, moduleSize)
            }
        }
    }

    // 添加定位标记（三个角）
    const drawPositionMarker = (x: number, y: number) => {
        ctx.fillStyle = '#000000'
        ctx.fillRect(x, y, moduleSize * 7, moduleSize * 7)
        ctx.fillStyle = '#ffffff'
        ctx.fillRect(x + moduleSize, y + moduleSize, moduleSize * 5, moduleSize * 5)
        ctx.fillStyle = '#000000'
        ctx.fillRect(x + moduleSize * 2, y + moduleSize * 2, moduleSize * 3, moduleSize * 3)
    }

    drawPositionMarker(0, 0) // 左上
    drawPositionMarker(18 * moduleSize, 0) // 右上
    drawPositionMarker(0, 18 * moduleSize) // 左下
}

const generateQRCodes = () => {
    environmentalModules.value.forEach(module => {
        const canvas = document.querySelector(`[data-ref="qr-${module.id}"]`) as HTMLCanvasElement
        if (canvas) {
            const qrData = `${selectedEnterprise.value?.name}-${module.qrData}`
            generateQRCode(canvas, qrData)
        }
    })
}

// 监听搜索关键词变化，重置页码
watch(searchKeyword, () => {
    currentPage.value = 1
})

// 生命周期
onMounted(async () => {
    // 生成模拟数据
   let res =  await getWrEnterpriseInfoAPI();
    allEnterprises.value =  res.data;

    // 默认选择第一个企业
    if (allEnterprises.value.length > 0) {
        selectedEnterprise.value = allEnterprises.value[0]
        nextTick(() => {
            generateQRCodes()
        })
    }
})

// 修复ref模板引用
const setQRRef = (el: HTMLCanvasElement | null, moduleId: number) => {
    if (el) {
        el.setAttribute('data-ref', `qr-${moduleId}`)
    }
}
</script>

<style scoped>
.enterprise-management {
    display: flex;
    height: 100vh;
    background: #f5f7fa;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 左侧边栏 */
.sidebar {
    width: 320px;
    background: #ffffff;
    border-right: 1px solid #e8eaed;
    display: flex;
    flex-direction: column;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
}

.search-container {
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
}

.search-box {
    position: relative;
    display: flex;
    align-items: center;
}

.search-icon {
    position: absolute;
    left: 12px;
    color: #9aa0a6;
    z-index: 1;
}

.search-input {
    width: 100%;
    padding: 12px 12px 12px 40px;
    border: 1px solid #dadce0;
    border-radius: 8px;
    font-size: 14px;
    outline: none;
    transition: all 0.2s;
    background: #f8f9fa;
}

.search-input:focus {
    border-color: #4285f4;
    background: #ffffff;
    box-shadow: 0 1px 6px rgba(66, 133, 244, 0.2);
}

.enterprise-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
}

.enterprise-item {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    margin: 4px 0;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s;
    position: relative;
}

.enterprise-item:hover {
    background: #f1f3f4;
}

.enterprise-item.active {
    background: #4285f4;
    color: white;
    box-shadow: 0 2px 8px rgba(66, 133, 244, 0.3);
}

.enterprise-icon {
    width: 32px;
    height: 32px;
    background: linear-gradient(135deg, #ff9a56, #ff6b9d);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
    color: white;
    flex-shrink: 0;
}

.enterprise-item.active .enterprise-icon {
    background: rgba(255, 255, 255, 0.2);
}

.enterprise-name {
    flex: 1;
    font-size: 14px;
    font-weight: 500;
}

.active-indicator {
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 分页控件 */
.pagination {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 16px;
    border-top: 1px solid #f0f0f0;
    gap: 12px;
}

.page-btn {
    width: 32px;
    height: 32px;
    border: 1px solid #dadce0;
    border-radius: 6px;
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s;
}

.page-btn:hover:not(:disabled) {
    background: #f8f9fa;
    border-color: #4285f4;
}

.page-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.page-info {
    font-size: 14px;
    color: #5f6368;
    min-width: 60px;
    text-align: center;
}

/* 主内容区域 */
.main-content {
    flex: 1;
    overflow-y: auto;
    background: #f5f7fa;
}

.content-container {
    padding: 32px;
    max-width: 1200px;
    margin: 0 auto;
}

.content-header {
    margin-bottom: 32px;
}

.enterprise-title {
    font-size: 24px;
    font-weight: 600;
    color: #202124;
    margin: 0 0 16px 0;
}

.header-divider {
    height: 3px;
    background: linear-gradient(90deg, #4285f4, #34a853);
    border-radius: 2px;
    width: 60px;
}

.modules-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 24px;
}

.module-card {
    background: white;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s;
    border: 1px solid #e8eaed;
}

.module-card:hover {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
    transform: translateY(-2px);
}

.card-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.card-left {
    flex: 1;
}

.module-title {
    font-size: 16px;
    font-weight: 600;
    color: #202124;
    margin: 0 0 8px 0;
}

.module-subtitle {
    font-size: 14px;
    color: #5f6368;
    margin: 0 0 20px 0;
}

.detail-btn {
    background: #4285f4;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
}

.detail-btn:hover {
    background: #3367d6;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(66, 133, 244, 0.3);
}

.card-right {
    margin-left: 24px;
}

.qr-code {
    width: 120px;
    height: 120px;
    border: 1px solid #e8eaed;
    border-radius: 8px;
    overflow: hidden;
    background: white;
}

.qr-canvas {
    width: 100%;
    height: 100%;
    display: block;
}

/* 空状态 */
.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #5f6368;
}

.empty-icon {
    margin-bottom: 16px;
    opacity: 0.5;
}

.empty-title {
    font-size: 20px;
    font-weight: 500;
    margin: 0 0 8px 0;
}

.empty-description {
    font-size: 14px;
    margin: 0;
}

/* 响应式设计 */
@media (max-width: 1024px) {
    .modules-grid {
        grid-template-columns: 1fr;
    }

    .sidebar {
        width: 280px;
    }
}

@media (max-width: 768px) {
    .enterprise-management {
        flex-direction: column;
    }

    .sidebar {
        width: 100%;
        height: 300px;
    }

    .content-container {
        padding: 16px;
    }

    .module-card {
        padding: 16px;
    }

    .card-content {
        flex-direction: column;
        text-align: center;
    }

    .card-right {
        margin-left: 0;
        margin-top: 16px;
    }
}

/* 滚动条样式 */
::-webkit-scrollbar {
    width: 6px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}
</style>